package com.pomelo.thread;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.SftpException;
import com.pomelo.config.FileConfig;
import lombok.Data;

import java.util.Stack;
import java.util.Vector;

@Data
public class FileThread implements Runnable {

    private ChannelSftp sftp;
    private ChannelSftp.LsEntry entry;

    public FileThread(ChannelSftp sftp, ChannelSftp.LsEntry entry) {
        this.sftp = sftp;
        this.entry = entry;
    }


    @Override
    public void run() {
        try {
            System.out.println(Thread.currentThread() + "正在运行");
            quickFindFile();
        } catch (SftpException e) {
            throw new RuntimeException(e);
        }
    }

    // 使用栈进行深度遍历
    private void quickFindFile() throws SftpException {
        Stack<ChannelSftp.LsEntry> stack = new Stack<>();
        stack.push(this.entry);
        ChannelSftp.LsEntry entry;
        if (!stack.isEmpty()) {
            entry = stack.pop();
            if (entry.getAttrs().isDir() && !"..".equals(entry.getFilename()) && !".".equals(entry.getFilename())) {
                String path ;
                if (entry.getFilename().equals(this.entry.getFilename())) {
                    path = FileConfig.getPath() + "/" + entry.getFilename();
                } else
                    path = FileConfig.getPath() + "/" + this.entry.getFilename() + "/" + entry.getFilename();
                System.out.println(path);
                Vector<ChannelSftp.LsEntry> ls = this.sftp.ls(path);
                if (ls != null) {
                    for (ChannelSftp.LsEntry l : ls) {
                        stack.push(l);
                    }
                }
            } else {
                System.out.println(entry.getFilename());
            }
        }

    }
}
